package com.hp.attendance.util;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/*")
public class MyFilter implements Filter {
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //过滤功能
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        String path = request.getContextPath();
        request.setAttribute("path",path);
        //判断用户是否登录过
        HttpSession session = request.getSession();
        Object emp = session.getAttribute("emp");
        if(emp==null){
            //如果我是请求的loginServlet 就需要放行 否则无法进行登录操作
            String requestURI = request.getRequestURI();
            if(requestURI.contains("login")
                    || requestURI.contains("code")
                || requestURI.contains("/css/")
                || requestURI.contains("/dist/")
                || requestURI.contains("/fonts/")
                || requestURI.contains("/img/")
                || requestURI.contains("/js/")
            ){
                filterChain.doFilter(request,response);
            }else{
                response.sendRedirect("/pages/login.jsp");
            }
            //如果没有登录 就拦截跳转到登录页面

//            request.getRequestDispatcher("/pages/login.jsp").forward(request,response);
        }else{
            //如果登录过就放行
            filterChain.doFilter(request,response);
        }

    }

    public void destroy() {
    }
}
